/*
 * @Author: 彭林
 * @Date: 2021-05-14 12:52:38
 * @LastEditTime: 2021-07-14 18:01:36
 * @LastEditors: 彭林
 * @Description:
 * @FilePath: /saas-app/app/service/campus.go
 */

package service

import (
	"saas-app/app/dao"
	"saas-app/app/define"
	"saas-app/app/model"

	"github.com/gogf/gf/database/gdb"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
)

type CampusRepository interface {
	CreateCampus(campus *model.Campus) bool
	GetCampusList(r *ghttp.Request, paging *define.PagingParams) (list gdb.Result, total int)
	GetCampusSimpleList(r *ghttp.Request) *gdb.Result
	UpdateCampus(*ghttp.Request, g.Map) bool
}

type campus struct{}

func CampusService() CampusRepository {
	return &campus{}
}

func (c campus) CreateCampus(campus *model.Campus) bool {
	_, err := dao.Campus.Save(campus)
	return err == nil
}

func (c campus) GetCampusList(r *ghttp.Request, pagingParams *define.PagingParams) (campusList gdb.Result, total int) {

	var (
		limit     = 10
		page      = 1
		school_id = r.GetCtxVar("school_id").Uint()
		user_id   = r.GetCtxVar("user_id").Uint()
	)

	if pagingParams.Page > 0 && pagingParams.Limit > 0 {
		page = pagingParams.Page
		limit = pagingParams.Limit
	}

	isAdmin := UserService().CheckSchoolAdmin(school_id, user_id)
	db := dao.Campus.Where("school_id = ?", school_id)
	if isAdmin {

		total, err := db.FindCount()

		if err != nil {
			panic(err)
		}

		campusList, err := db.Limit(limit).Offset((page - 1) * limit).FindAll()

		if err != nil {
			panic(err)
		}

		return campusList, total

	} else {
		campusIdList := UserService().GetCampusIdList(school_id, user_id)
		if campusIdList == nil {
			panic("暂无校区")
		}
		db = db.Where("id in (?)", campusIdList)

		total, err := db.FindCount()

		if err != nil {
			panic(err)
		}

		campusList, err := db.Offset((page - 1) * limit).Limit(limit).FindAll()

		if err != nil {
			panic(err)
		}
		return campusList, total
	}
}

func (c campus) GetCampusSimpleList(r *ghttp.Request) (campusList *gdb.Result) {

	school_id := r.GetCtxVar("school_id").Uint()
	user_id := r.GetCtxVar("user_id").Uint()
	isAdmin := UserService().CheckSchoolAdmin(school_id, user_id)

	if isAdmin {
		campusList, err := dao.Campus.Where("school_id = ?", school_id).FindAll()
		if err != nil {
			panic(err)
		}
		return &campusList
	} else {
		if campusIdList := UserService().GetCampusIdList(school_id, user_id); campusIdList == nil {
			panic("暂无校区")
		} else {

			campusList, err := dao.Campus.Where("school_id = ?", school_id).Where("id in (?)", campusIdList).FindAll()

			if err != nil {
				panic(err)
			}

			return &campusList
		}

	}
}

func (c campus) UpdateCampus(r *ghttp.Request, data map[string]interface{}) bool {
	campusId := r.GetQueryUint("campus_id")
	if _, err := dao.Campus.Where("id = ?", campusId).Update(data); err != nil {
		panic(err)
	}
	return true
}
